<?php


namespace app\circularlinklist\controller;


class CircularLinkedList
{
    private $header;    // 头节点

    function __construct($data) {
        $this->header = new Node($data);
        $this->header->next = $this->header;
    }
    // 查找节点
    public function find($item) {
        $current = $this->header;
        while ($current->data != $item) {
            $current = $current->next;
        }
        return $current;
    }
    // 插入新节点
    public function insert($item, $new) {
        $newNode = new Node($new);
        $current = $this->find($item);
        if ($current->next != $this->header) { // 链表中间
            $current->next = $newNode;
            $newNode->next = $current->next;
        } else { // 链表尾端
            $current->next = $newNode;
            $newNode->next = $this->header;
        }
        return true;
    }
    // 删除节点
    public function delete($item) {
        $current = $this->header;
        while ($current->next != null && $current->next->data != $item) {
            $current = $current->next;
        }
        if ($current->next != $this->header) { // 链表中间
            $current->next = $current->next->next;
        } else { // 链表尾端
            $current->next = $this->header;
        }
    }
    // 显示链表中的元素
    public function display() {
        $current = $this->header;
        while ($current->next != $this->header) {
            echo $current->next->data . "&nbsp;&nbsp;&nbsp";
            $current = $current->next;
        }
    }
}